package com.thinkersre.util;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Component
public class SensitiveFilter {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);

    //替换符号
    private static final String REPLACEMENT = "***";
    //根节点
    private TrieNode rootNode = new TrieNode();

    @PostConstruct
    public void init(){
        //读取类加载器
        try (
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                ){
            String keyword;
            while((keyword = bufferedReader.readLine())!=null){
                //添加到前缀树
                this.addKeyWord(keyword);
            }
        } catch (IOException e) {
        logger.error("加载敏感词失败:"+e.getMessage());
        }
    }

    //将一个敏感词添加到前缀树中
    private void addKeyWord(String keyword){
        //设置初始结点
        TrieNode tempNode = rootNode;
        for (int i = 0;i< keyword.length();i++){
            //读取字符
            char c = keyword.charAt(i);
            //根据读取到的字符来查找得到下一结点或空
            TrieNode subNode = tempNode.getSubNode(c);
            //如果是null的话代表该结点没有当前敏感词字符，那么该结点可以被加入显示
            if (subNode == null){
                //初始化子节点
                subNode = new TrieNode();
                //加入显示
                tempNode.addSubNode(c,subNode);
            }
            //指向子节点，进入下一轮循环
            tempNode = subNode;
            // 设置结束标识
            if (i == keyword.length() - 1) {
                tempNode.setKeywordEnd(true);
            }
        }

    }

    /**
     * 过滤敏感词
     * @param text 待过滤的文本
     * @return 过滤后的文本
     */
    public String Filter(String text){
        if(StringUtils.isBlank(text)){
            return null;
        }
        //指针1
        TrieNode tempNode= rootNode;
        //指针2
        int begin = 0;
        //指针3
        int position = 0;
        //结果
        StringBuilder stringBuilder = new StringBuilder();
        while(position<text.length()){
            //当前读取到的敏感词字符
            char character = text.charAt(position);
            //跳过符号
            if (isSymbol(character)){
                //若指针1处于根结点，将此符号计入结果,让指针2向后走一步
                if(tempNode == rootNode){
                    stringBuilder.append(character);
                    begin++;
                }
                position++;
                continue;
            }
            //根据当前读到的敏感词字符查询下一个结点是否是敏感词字符
            tempNode = tempNode.getSubNode(character);
            //tempNode为null，代表不是敏感词字符
            if (tempNode == null){
                //不是敏感词字符，加入stringBuilder可变字符序列
                stringBuilder.append(text.charAt(begin));
                //进入下一个位置
                position = ++begin;
                //重新指向根结点
                tempNode = rootNode;
            }else if (tempNode.isKeyWordEnd()){
                //发现敏感词，进行替换
                stringBuilder.append(REPLACEMENT);
                //加入下一个位置
                begin = ++position;
                //重新指向根结点
                tempNode = rootNode;
            }else {
                //继续检查下一个字符
                position++;
            }

        }
        //将最后一批传入结果
        stringBuilder.append(text.substring(begin));
        return stringBuilder.toString();


    }

    //判断是否为符号
    private boolean isSymbol(Character character){
        //0x2E80-0x9FFF为东亚文字范围
        //条件1:非普通字符 条件2:非东亚文字
        return !CharUtils.isAsciiAlphanumeric(character)&&(character < 0x2E80 || character > 0x9FFF);
//        return true;
//        return character.equals('的')||character.equals('是')||character.equals('啊');
    }

    //前缀树
    private class TrieNode{
        //关键词结束标识
        private boolean isKeyWordEnd = false;
        //子节点(key是下级字符，value是下级节点
        private Map<Character,TrieNode> subNodes = new HashMap<>();
        public boolean isKeyWordEnd() {
            return isKeyWordEnd;
        }
        public void setKeywordEnd(boolean keyWordEnd) {
            isKeyWordEnd = keyWordEnd;
        }
        //添加子节点
        public void addSubNode(Character character,TrieNode trieNode){
            subNodes.put(character,trieNode);
        }
        //获取子节点
        public TrieNode getSubNode(Character character){
            return subNodes.get(character);
        }

    }
}
